package com.zf.common.http.controller;

import com.zf.common.http.entity.FileFormEntity;
import com.zf.common.http.entity.PaperEntity;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.List;
import java.util.StringJoiner;

/**
 * 测试 Http Interface
 */
@Slf4j
@RestController
@RequestMapping("/test-http-interface")
public class TestHttpInterfaceController {

    /**
     * post json
     */
    @PostMapping(value = "/postJson")
    public String postJson(@RequestBody PaperEntity entity) {
        log.info("PaperEntity: {}", entity);
        return "post json success";
    }


    /**
     * post form
     */
    @PostMapping(value = "/postForm")
    public String postForm(FileFormEntity formEntity, HttpServletRequest request) throws IOException {
        StringJoiner headersStr = new StringJoiner("\n");
        Enumeration<String> headerNameElements = request.getHeaderNames();
        while (headerNameElements.hasMoreElements()) {
            String headerName = headerNameElements.nextElement();
            headersStr.add(MessageFormat.format("{0}:{1}", headerName, request.getHeader(headerName)));
        }
        System.out.println(headersStr);

        log.info("username: {}, age: {}", formEntity.getUsername(), formEntity.getAge());

        List<MultipartFile> attachFileList = formEntity.getAttachFileList();
        if (!CollectionUtils.isEmpty(attachFileList)) {
            for (MultipartFile file : attachFileList) {
                // 文件名
                String originalFilename = file.getOriginalFilename();
                // 获取文件输入流
                InputStream inputStream = file.getInputStream();
                // 读取输入流内容
                byte[] fileBytes = FileCopyUtils.copyToByteArray(inputStream);
                log.info("originalFilename: {}, size: {}", originalFilename, fileBytes.length);
            }
        }
        return "post form success";
    }

}
